const express = require('express');
const cors = require('cors');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();
const PORT = process.env.PROXY_PORT || 3001; // Proxy server port
const API_TARGET = process.env.API_TARGET || 'http://localhost:3000'; // Backend API target

app.use(cors()); // Enable CORS for all requests

// Proxy API requests
app.use('/api', createProxyMiddleware({ 
  target: API_TARGET, 
  changeOrigin: true,
  onProxyReq: (proxyReq, req) => { // Removed 'res' from here
    console.log(`Proxying request: ${req.method} ${req.url} -> ${API_TARGET}${req.url}`);
  },
  onError: (err, req, res) => {
    console.error('Proxy error:', err);
    res.writeHead(500, {
      'Content-Type': 'text/plain',
    });
    res.end('Something went wrong with the proxy.');
  },
}));

app.listen(PORT, () => {
  console.log(`Proxy server listening on port ${PORT}, proxying to ${API_TARGET}`);
});
